package main

import (
	"google.golang.org/grpc"
	pb "grpc-demo/complex/proto"
	"io"
	"log"
	"net"
	"strconv"
)

// StreamServer is the server API for Stream service.
type StreamServerImpl struct {
	pb.UnimplementedStreamServer
}

func (s *StreamServerImpl) Conversation(srv pb.Stream_ConversationServer) error {
	n := 1
	for {
		req, err := srv.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}
		err = srv.Send(&pb.StreamResponse{
			StreamValue: "from stream server: the " + strconv.Itoa(n) + " question is " +
				req.StreamData})
		if err != nil {
			return err
		}
		log.Println("from stream client question is ", req.StreamData)
		n++
	}
	return nil
}

func main() {
	// 监听端口
	listener, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	log.Println("50051端口正在监听...")
	// 新建grpc服务器实例
	grpcServer := grpc.NewServer()

	// 注册服务
	pb.RegisterStreamServer(grpcServer, &StreamServerImpl{})

	// 启动服务
	if err = grpcServer.Serve(listener); err != nil {
		log.Fatal(err)
	}
}
